package com.guiji.quartz.service;

import cn.hutool.crypto.SecureUtil;
import com.guiji.common.utils.spring.SpringUtils;
import com.guiji.quartz.domain.SpiderNews;
import org.redisson.api.RSetCache;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @program: cms-vue-plus
 * @description: redis工具类
 * @author: gaoX
 * @create: 2021-08-10 13:55
 **/
@Component
public class RedisService implements InitializingBean {

	private static final Logger log = LoggerFactory.getLogger(RedisService.class);

	private static String key = "title_md5";

	@Autowired
	private RedissonClient redissonClient;

	/**
	 * 初始化redis，mysql数据存入redis
	 */
	public void init() {
		ISpiderNewsService service = SpringUtils.getBean(ISpiderNewsService.class);
		List<SpiderNews> list = service.list();
		RSetCache<String> cache = redissonClient.getSetCache(key);
		cache.delete();
		list.forEach(s -> {
			cache.add(SecureUtil.md5(s.getNewsTitle()), 14, TimeUnit.DAYS);
		});

	}

	/**
	 * 查询MD5过后的id是否存在于redis
	 *
	 * @param md5
	 * @return
	 */
	public boolean isMember(String md5) {
		Boolean isMember = redissonClient.getSetCache(key).contains(md5);
		return isMember;
	}

	/**
	 * 插入redis的set中
	 *
	 * @param md5
	 */
	public void addTitleSet(String md5,String category,Date time,String title) {
		//记录爬取成功的日志
		log.info("时间{}，爬取目录-{}-， {}",time,category,title);
		redissonClient.getSetCache(key).add(md5, 14, TimeUnit.DAYS);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
//		init();
	}
}
